package com.bestcem.xm.ticket.util;

import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.user.GroupDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.GroupNodeDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.UserDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.UserRoleDTO;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.util.*;

/**
 * 工单使用 通用工具类
 *
 * @author liheng
 * @version v1.0
 * @date 2021/8/20 11:24
 */
@Component
public class CommonUtils {
    @Resource
    private TicketUserGrpcService ticketUserGrpcService;
    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;

    private static final String[] ESCAPE_CHAR =
            {"\\*", "\\.", "\\?", "\\+", "\\$", "\\^", "\\[", "\\]", "\\(", "\\)", "\\{", "\\}", "\\|", "\\/"};

    /**
     * 获取用户所属区域的下属所有区域
     *
     * @param userId 用户id
     * @return 所有 region
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/9/28 10:53
     */
    public List<String> getUserAllRegions(String userId) {
        List<String> groupIdList = ticketUserGrpcService.listAncestorIdsByUserId(userId);
        if (CollectionUtils.isEmpty(groupIdList)) {
            return new ArrayList<>();
        }
        String currentGroupId = groupIdList.get(0);
        // 该用户有权限查看的组织
        List<GroupNodeDTO> groupNodeDTOList = ticketUserGrpcService.listSubGroupsByGroupIdsAndLevelId(Arrays.asList(currentGroupId), null);
        List<String> subGroupIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupNodeDTOList)) {
            for (GroupNodeDTO groupNodeDTO : groupNodeDTOList) {
                if (Objects.nonNull(groupNodeDTO)) {
                    subGroupIdList.add(groupNodeDTO.getId());
                }
            }
        }
        // 最高层级用户可见所有无归属的工单
        if (groupIdList.size() == 1) {
            subGroupIdList.add("");
        }
        return subGroupIdList;
    }


    /**
     * 获取用户当前所属区域及下属所有区域
     *
     * @param userId 用户id
     * @return 所有 region
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/9/28 10:53
     */
    @Nonnull
    public List<String> getUserAllGroupId(String userId) {
        List<String> subGroupIdList = new ArrayList<>();
        List<String> userCurrentGroup = getUserCurrentGroupId(userId);
        if (CollectionUtils.isEmpty(userCurrentGroup)) {
            return subGroupIdList;
        }

        // 最高层级用户可见所有无归属的工单
        if (userCurrentGroup.size() == 1) {
            subGroupIdList.add("");
        }
        // 该用户有权限查看的组织
        List<GroupNodeDTO> groupNodeDTOList = ticketUserGrpcService.listSubGroupsByGroupIdsAndLevelId(userCurrentGroup, null);
        if (!CollectionUtils.isEmpty(groupNodeDTOList)) {
            for (GroupNodeDTO groupNodeDTO : groupNodeDTOList) {
                if (Objects.nonNull(groupNodeDTO)) {
                    subGroupIdList.add(groupNodeDTO.getId());
                }
            }
        }
        return subGroupIdList;
    }


    /**
     * 获取用户当前所属区域
     *
     * @param userId 用户id
     * @return 用户当前所属region
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/12/30 11:25
     */
    @Nonnull
    public List<String> getUserCurrentGroupId(String userId) {
        List<String> result = new ArrayList<>();
        List<GroupDTO> userCurrentGroup = ticketUserGrpcService.getUserCurrentGroup(userId);
        if (CollectionUtils.isEmpty(userCurrentGroup)) {
            return result;
        }
        for (GroupDTO groupDTO : userCurrentGroup) {
            if (cn.hutool.core.lang.ObjectId.isValid(groupDTO.getId())) {
                result.add(groupDTO.getId());
            }
        }
        return result;
    }


    /**
     * 获取用户所属所有角色
     *
     * @param userId 用户id
     * @return 所有角色id 的 ObjectId
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/9/28 10:53
     */
    @Nonnull
    public List<ObjectId> getUserAllRoleObjectId(String userId) {
        List<ObjectId> roleObjectIds = new ArrayList<>();
        List<String> userAllRoleId = getUserAllRoleId(userId);
        if (!CollectionUtils.isEmpty(userAllRoleId)) {
            for (String s : userAllRoleId) {
                roleObjectIds.add(new ObjectId(s));
            }
        }
        return roleObjectIds;
    }


    /**
     * 获取用户所属所有角色
     *
     * @param userId 用户id
     * @return 所有角色id
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/9/28 10:53
     */
    public List<String> getUserAllRoleId(String userId) {
        List<String> roleIds = new ArrayList<>();
        List<UserRoleDTO> userRoles = ticketBaseUserGrpcService.getUserRole(userId);
        if (!CollectionUtils.isEmpty(userRoles)) {
            for (UserRoleDTO userRole : userRoles) {
                roleIds.add(userRole.getRoleId());
            }
        }
        return roleIds;
    }


    /**
     * 获取租户下所有系统管理员的 userId
     *
     * @param orgId 租户id
     * @return 所有系统管理员的 userId
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/12/29 15:59
     */
    @Nonnull
    public Set<String> getOrgAllAdminId(String orgId) {
        Set<String> result = new HashSet<>();
        if (cn.hutool.core.lang.ObjectId.isValid(orgId)) {
            List<String> adminIds = ticketUserGrpcService.listAdminIds(orgId);
            if (!CollectionUtils.isEmpty(adminIds)) {
                result.addAll(adminIds);
            }
        }
        return result;
    }


    /**
     * 获取租户下所有系统管理员的 user info
     *
     * @param orgId 租户id
     * @return 所有系统管理员的 user info
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/12/31 14:54
     */
    @Nonnull
    public List<UserDTO> getOrgAllAdminUser(String orgId) {
        if (cn.hutool.core.lang.ObjectId.isValid(orgId)) {
            List<String> adminIds = ticketUserGrpcService.listAdminIds(orgId);
            if (!CollectionUtils.isEmpty(adminIds)) {
                List<UserDTO> userDTOS = ticketBaseUserGrpcService.listUserByIds(adminIds);
                if (!CollectionUtils.isEmpty(userDTOS)) {
                    return userDTOS;
                }
            }
        }
        return new ArrayList<>();
    }

    /**
     * 将字符串里所有的正则符号替换为转义符
     *
     * @param str 目标字符串
     * @return 替换后的字符串
     */
    public static String escapeRegexChar(String str) {
        str = str.replaceAll("\\\\", "\\\\\\\\");
        for (String regex : ESCAPE_CHAR) {
            str = str.replaceAll(regex, "\\" + regex);
        }
        return str;
    }
}
